//
//  MyBidViewController.swift
//  cxd4iphone
//
//  Created by hexy on 12/3/15.
//  Copyright © 2015 hexy. All rights reserved.
//

import UIKit

class MyInvestViewController: BaseTableViewController {

    private lazy var myInvestListViewModel = MyInvestListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadData(true)
    }
    
    private func loadData(pullDown: Bool) {
        
        xx_showHUD(nil)
        myInvestListViewModel.loadUserInvestRecord(pullDown).subscribeError({ (error) -> Void in
            
            xx_showError(error)
            
            }) { () -> Void in
                
                xx_hideHUD()
                let mo = self.myInvestListViewModel.sections[0]
                
                for vm in mo {
                    
                    let vm = vm as! MyInvestCellViewModel
                    
                    vm.aSetRepayPlanBtnClickBlock({ (vm) -> Void in
                        
                        guard let loanId = vm.bidModel.id else { return }
                        
                        self.pushToRepayPlan(loanId)
                    })
                    
                    vm.aSetloanPactBtnClickBlock({ (vm) -> Void in
                        
                        guard let contractUrl = vm.bidModel.contractUrl else { return }
                        
                        self.pushToLoanPact(contractUrl)
                    })
                }
                self.tableView.reloadData()
                self.navigationItem.rightBarButtonItem = UIBarButtonItem(target: self, action: "showPickerView")
        }
    }
    
    func pushToRepayPlan(loanId: String) {
        
        self.navigationController?.pushViewController(RepayPlanViewController(loanId: loanId), animated: true)
    }
    
    func pushToLoanPact(contractUrl: String) {
        
        xx_print(contractUrl)
        self.navigationController?.pushViewController(WebViewController(title: "借款合同", URLStr: contractUrl), animated: true)
    }
    
    func showPickerView() {
        
        let pick = PickerView()
        pick.show(myInvestListViewModel.pickerViewModel) { (rows) -> Void in
            
            let pvm = self.myInvestListViewModel.pickerViewModel
            
            let status = (pvm.components[0][rows[0]]).status
            
            
            let qm = self.myInvestListViewModel.queryModel
            
            qm.status = status
            
            self.loadData(true)
        }
    }


    override func makeTableView() {
        
        
        tableView.rowHeight = xx_height(200)
        
        self.tableListViewModel = myInvestListViewModel
        tableView.registerClass(MyInvestListCell.self, forCellReuseIdentifier: MyInvestCellReuseID)
        tableView.sectionFooterHeight = 0.1
        
        
    }
    
}
